﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FindLinkRegister
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Properties
        bool flagSearch = true;
        List<WebsiteDTO> _lstWebsite;
        public static List<WebsiteDTO> _lstResults = new List<WebsiteDTO>();
        int _startNumber = 0;
        int _endNumber = 5;

        /// <summary>
        /// Đọc dữ liệu link website lên listview
        /// </summary>
        private void LoadDataToListView()
        {
            try
            {
                _lstWebsite = WebsiteDAO.GetAllLink();
                if (_lstWebsite != null)
                {
                    int count = 0;
                    foreach (WebsiteDTO website in _lstWebsite)
                    {
                        ListViewItem item = new ListViewItem(count.ToString());
                        item.SubItems.Add(website.LinkWebsite.ToString());
                        lvListLink.Items.Add(item);
                        count++;
                    }
                    lblTextListLink.Text = "List link: " + _lstWebsite.Count.ToString();
                }
                else
                {
                    MessageBox.Show("Database is null");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("***ERROR LOAD DB\n"+ ex.ToString());
                lvListLink.Items.Clear();
                return;
            }
        }

        /// <summary>
        /// Load kết quả sau khi tìm link
        /// </summary>
        public void LoadResultToListView()
        {
            lvResult.Items.Clear();
            _lstResults.Clear();
            lblTextListResult.Text = "";

            // mỗi lần chạy 1 phần dữ liệu
            _startNumber = int.Parse(txtFrom.Text.ToString());
            _endNumber = int.Parse(txtTo.Text.ToString());

            // progressbar
            this.progressBar1.Minimum = 0;
            this.progressBar1.Maximum = _endNumber - _startNumber;
            this.progressBar1.Step = 1;
            this.progressBar1.Value = 1;

            if (_lstWebsite == null || _startNumber > _endNumber || _endNumber >= _lstWebsite.Count)
            {
                MessageBox.Show("Input ERROR!");
                return;
            }
            RequestHandle.countFound = 0;
            if(flagSearch) // tim link register
                for(int i = _startNumber; i < _endNumber; i++)
                {
                    // lấy link đăng ký
                    FAP_Cores.FapThread.ThreadControl.AddTasks(new TaskRegister(_lstWebsite[i].LinkWebsite));
                    this.progressBar1.PerformStep();
                }
            else // tim link login
                for (int i = _startNumber; i < _endNumber; i++)
                {
                    // lấy link đăng ký
                    FAP_Cores.FapThread.ThreadControl.AddTasks(new TaskLogin(_lstWebsite[i].LinkWebsite));
                    this.progressBar1.PerformStep();
                }

        }

        /// <summary>
        /// Update UI ListView Result
        /// </summary>
        public void UpdateUIListViewResult()
        {
            // update UI
            if (_lstResults.Count > 0)
            {
                lvResult.Items.Clear();
                int count = 0;
                for (int j = 0; j < _lstResults.Count; j++)
                {
                    count++;
                    ListViewItem item = new ListViewItem(count.ToString());
                    item.SubItems.Add(_lstResults[j].LinkWebsite);
                    item.SubItems.Add(_lstResults[j].LinkResult);
                    lvResult.Items.Add(item);
                }
                lblTextListResult.Text = "List results: " + RequestHandle.countFound + "/" + _lstResults.Count.ToString();
            }
        }


        // //////////////////////////////////////////////////
        // Control
        // //////////////////////////////////////////////////

        private void Form1_Load(object sender, EventArgs e)
        {
            _lstWebsite = new List<WebsiteDTO>();
            // load data
            LoadDataToListView();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            flagSearch = true;
            LoadResultToListView();
        }

        private void lvListLink_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void btnUpdateDB_Click(object sender, EventArgs e)
        {
            if (_lstResults != null)
            {
               
                DialogResult result = MessageBox.Show("Update Database???", "Update " + _lstResults.Count.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    int count = 0;
                    // update link register
                    if(flagSearch)
                        foreach (WebsiteDTO item in _lstResults)
                        {
                            count += WebsiteDAO.UpdateLinkRegister(item.LinkWebsite, item);
                        }
                    else // update link login
                        foreach (WebsiteDTO item in _lstResults)
                        {
                            count += WebsiteDAO.UpdateLinkLogin(item.LinkWebsite, item);
                        }
                    MessageBox.Show("Updated " + count.ToString() + " rows");
                }
            }
            else
            {
                MessageBox.Show("Data is NULL");
            }
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            if (_lstResults != null)
            {
                DialogResult result = MessageBox.Show("Clear list???", "Clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    _lstResults.Clear();
                    lvResult.Items.Clear();
                    lblTextListResult.Text = "";
                }
            }
        }

        private void txtFrom_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }

        private void txtTo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }

        private void btnRefesh_Click(object sender, EventArgs e)
        {
            // update UI
            UpdateUIListViewResult();
        }

        private void btnGetLogin_Click(object sender, EventArgs e)
        {
            flagSearch = false;
            LoadResultToListView();
        }
    }


    // /////////////////////////////
    // CLASS
    // /////////////////////////////
    public class TaskRegister : FAP_Cores.FapThread.SampleTask
    {
        private string link;

        public TaskRegister(string url)
        {
            link = url;
        }

        public override void DoWork()
        {
            RequestHandle.GetLinkRegisterByLinks(this.link);
        }
    }

    public class TaskLogin : FAP_Cores.FapThread.SampleTask
    {
        private string link;

        public TaskLogin(string url)
        {
            link = url;
        }

        public override void DoWork()
        {
            RequestHandle.GetLinkLoginByLinks(this.link);
        }
    }
}
